package per.sen.shopping.infrastructure.repository;

import io.smallrye.mutiny.Uni;
import io.vertx.mutiny.sqlclient.Row;
import io.vertx.mutiny.sqlclient.RowSet;
import io.vertx.mutiny.sqlclient.Tuple;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import per.sen.shopping.infrastructure.common.exception.BaseException;
import per.sen.shopping.infrastructure.configuration.DynamicReactiveSqlClientSelector;
import per.sen.shopping.infrastructure.utils.RowToClazzUtil;
import per.sen.shopping.model.po.SysBackendUserPO;

import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class SysBackendUserReadRepository {

    @Inject
    DynamicReactiveSqlClientSelector sqlClientSelector;

    public Uni<List<SysBackendUserPO>> findByUserMobile(String userMobile){
        List<SysBackendUserPO> sysBackendUserPOList = new ArrayList<>();
        return  sqlClientSelector.selectClient(true).chain(slaveClient-> slaveClient.preparedQuery("select * from sys_backend_user where user_mobile = ? ")
                .execute(Tuple.of(userMobile))
                .onItem().transform(RowSet::iterator)
                .onItem().invoke(iterator -> {
                    while (iterator.hasNext()) {
                        Row next = iterator.next();
                        SysBackendUserPO convert = null;
                        try {
                            convert = RowToClazzUtil.convert(next,SysBackendUserPO.class);
                        } catch (BaseException e) {
                            throw new RuntimeException(e);
                        }
                        sysBackendUserPOList.add(convert);
                    }
                }).onItem().transformToUni(execute -> Uni.createFrom().item(sysBackendUserPOList)));
    }


    public Uni<List<SysBackendUserPO>> findByUsername(String username) {
        List<SysBackendUserPO> sysBackendUserPOList = new ArrayList<>();
        return  sqlClientSelector.selectClient(true).chain(slaveClient-> slaveClient.preparedQuery("select * from sys_backend_user where username = ? ")
                .execute(Tuple.of(username))
                .onItem().transform(RowSet::iterator)
                .onItem().invoke(iterator -> {
                    while (iterator.hasNext()) {
                        Row next = iterator.next();
                        SysBackendUserPO convert = null;
                        try {
                            convert = RowToClazzUtil.convert(next,SysBackendUserPO.class);
                        } catch (BaseException e) {
                            throw new RuntimeException(e);
                        }
                        sysBackendUserPOList.add(convert);
                    }
                }).onItem().transformToUni(execute -> Uni.createFrom().item(sysBackendUserPOList)));

    }
}
